package model

import (
	"context"
	"errors"
	"fmt"
	"time"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/schema"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logc"

	"gorm.io/gorm"
)

type AdminLoginToken struct {
	ctx context.Context
	db  *gorm.DB
}

func NewAdminLoginToken(ctx context.Context, db *gorm.DB) *AdminLoginToken {
	return &AdminLoginToken{
		ctx: ctx,
		db:  db,
	}
}

func (model *AdminLoginToken) getDb() *gorm.DB {
	if model.db != nil {
		return model.db
	}

	return svc.Db
}

func (model *AdminLoginToken) GetAdminUserLoginTokenByUserIdAndSource(userId int64, source, business string) (id int64, err error) {
	dbRes := model.getDb().Model(&schema.AdminLoginToken{}).Select("id").Where("user_id =? and source = ? and business = ?", userId, source, business).First(&id)
	if err = dbRes.Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return 0, fmt.Errorf("GetAdminUserLoginTokenByUserIdAndSource error: %v", err)
	}

	return id, nil
}

func (model *AdminLoginToken) InsertAdminUserLoginToken(data *schema.AdminLoginToken) error {
	data.CreatedAt = time.Now().Unix()
	data.UpdatedAt = time.Now().Unix()
	dbRes := model.getDb().Model(&schema.AdminLoginToken{}).Create(data)
	if err := dbRes.Error; err != nil {
		logc.Error(model.ctx, "AdminLoginToken-InsertUserLoginToken,err:", err)
		return err
	}

	return nil
}

func (model *AdminLoginToken) UpdateAdminUserLoginToken(id int64, token string, userId int64) error {
	dbRes := model.getDb().Model(&schema.AdminLoginToken{}).Where("id=?", id).Update("sign", token)
	if err := dbRes.Error; err != nil {
		logc.Error(model.ctx, "AdminLoginToken-UpdateUserLoginToken,err:", err)
		return err
	}

	return nil
}

func (model *AdminLoginToken) GetAdminSignByUserIdAndPlatform(userId int64, platform string, business string) (sign string, err error) {
	dbRes := model.getDb().Model(&schema.AdminLoginToken{}).Select("sign").Where("user_id =? and source = ? and business=?", userId, platform, business).First(&sign)
	if err := dbRes.Error; err != nil && err != gorm.ErrRecordNotFound {
		logc.Error(model.ctx, "AdminLoginToken-GetSignByUserIdAndPlatform,err:", err)
		return sign, err
	}

	return sign, nil
}

func (model *AdminLoginToken) CleanAllLoginTokenOfUser(userIds ...int64) error {
	dbRes := model.getDb().Unscoped().Delete(&schema.AdminLoginToken{}, "user_id in ?", userIds)
	if err := dbRes.Error; err != nil {
		return fmt.Errorf("clean login token error: %v", err)
	}

	return nil
}

func (model *AdminLoginToken) List(userIds ...int64) (tokens []*schema.AdminLoginToken) {
	model.getDb().Model(&schema.AdminLoginToken{}).Where("user_id in ?", userIds).Find(&tokens)
	return
}
